C++ Primer, Fifth Edition by Stanley B. Lippman & Josée Lajoie & Barbara Moo

C++ Primer, Fifth Edition by Stanley B. Lippman & Josée Lajoie & Barbara Moo

Author:Stanley B. Lippman & Josée Lajoie & Barbara Moo [Lippman, Stanley B. & Lajoie, Josée & Moo, Barbara]
Language: eng
Format: epub
Publisher: Pearson Education
Published: 2012-08-06T05:00:00+00:00


* * *

Best Practices

You can avoid all of these problems by using smart pointers exclusively. The smart pointer will take care of deleting the memory only when there are no remaining smart pointers pointing to that memory.

* * *

* * *

Resetting the Value of a Pointer after a delete ...

When we delete a pointer, that pointer becomes invalid. Although the pointer is invalid, on many machines the pointer continues to hold the address of the (freed) dynamic memory. After the delete, the pointer becomes what is referred to as a dangling pointer. A dangling pointer is one that refers to memory that once held an object but no longer does so.

Dangling pointers have all the problems of uninitialized pointers (§ 2.3.2, p. 54). We can avoid the problems with dangling pointers by deleting the memory associated with a pointer just before the pointer itself goes out of scope. That way there is no chance to use the pointer after the memory associated with the pointer is freed. If we need to keep the pointer around, we can assign nullptr to the pointer after we use delete. Doing so makes it clear that the pointer points to no object.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.